<template>
  <!-- 查看协议对话框 -->
  <a-modal
    v-model:open="modalVisible"
    title="查看协议详情"
    width="1000px"
    :footer="null"
    class="protocol-view-modal"
    @cancel="closeModal"
  >
    <a-descriptions bordered>
      <a-descriptions-item label="协议ID">
        {{ viewingProtocol.protocolId }}
      </a-descriptions-item>
      <a-descriptions-item label="协议名称">
        {{ viewingProtocol.name }}
      </a-descriptions-item>
      <a-descriptions-item label="版本">
        {{ viewingProtocol.version }}
      </a-descriptions-item>

      <a-descriptions-item label="协议类型">
        <a-tag :color="getProtocolTypeColor(viewingProtocol.protocolType)">
          {{ getProtocolTypeName(viewingProtocol.protocolType) }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="状态">
        <a-tag :color="viewingProtocol.enabled ? 'green' : 'red'">
          {{ viewingProtocol.enabled ? "启用" : "禁用" }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="创建时间">
        {{ viewingProtocol.metadata?.createTime }}
      </a-descriptions-item>

      <a-descriptions-item label="描述" :span="3">
        {{ viewingProtocol.description }}
      </a-descriptions-item>

      <a-descriptions-item label="配置段数量">
        {{ viewingProtocol.configSections?.length || 0 }}
      </a-descriptions-item>
      <a-descriptions-item label="字段总数">
        {{ getTotalFieldsCount(viewingProtocol) }}
      </a-descriptions-item>
      <a-descriptions-item label="必填字段数">
        {{ getRequiredFieldsCount(viewingProtocol) }}
      </a-descriptions-item>
    </a-descriptions>

    <a-divider>配置段详情</a-divider>
    <a-collapse>
      <a-collapse-panel
        v-for="section in viewingProtocol.configSections"
        :key="section.sectionKey"
        :header="`${section.sectionName} (${section.fields?.length || 0} 个字段)`"
      >
        <a-table
          :dataSource="section.fields"
          :columns="fieldColumns"
          :pagination="false"
          size="small"
        />
        
        <!-- 显示该配置段的默认值 -->
        <div style="margin-top: 16px;">
          <h4 style="font-size: 14px; color: #666; margin-bottom: 8px;">默认值配置</h4>
          <a-descriptions size="small" bordered :column="2">
            <a-descriptions-item
              v-for="field in section.fields"
              :key="field.fieldKey"
              :label="field.fieldName"
            >
              <a-tag v-if="field.defaultValue" color="blue">{{ field.defaultValue }}</a-tag>
              <span v-else style="color: #ccc;">无默认值</span>
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </a-collapse-panel>
    </a-collapse>

    <!-- 协议默认值摘要 - 分段JSON显示 -->
    <a-divider>协议默认值摘要</a-divider>
    <a-collapse>
      <a-collapse-panel
        v-for="section in viewingProtocol.configSections"
        :key="section.sectionKey"
        :header="`${section.sectionName} - 默认值配置 (${getSectionDefaultValuesCount(section)} 个)`"
      >
        <div v-if="getSectionDefaultValuesCount(section) > 0" class="section-json-display">
          <pre style="font-size: 12px; margin: 0; background-color: #f8f9fa; border: 1px solid #e9ecef; color: #495057; padding: 12px; border-radius: 6px;">{{ JSON.stringify(getSectionDefaultValues(section), null, 2) }}</pre>
        </div>
        <div v-else style="color: #999; text-align: center; padding: 20px;">
          此配置段没有设置默认值
        </div>
      </a-collapse-panel>
    </a-collapse>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import {
  ProtocolType3,
  type MerchantChannelConfig3,
  type QRCodeConfig,
  type DefaultProtocol,
  ProtocolConfigUtils,
} from "../../types/protocol3-types";
import { ProtocolTypeNumber } from "./types";

// 响应式数据
const modalVisible = ref(false);
const viewingProtocol = reactive<MerchantChannelConfig3 | QRCodeConfig>({} as any);

// 字段表格列定义
const fieldColumns = [
  { title: "字段ID", dataIndex: "fieldKey", key: "fieldKey" },
  { title: "标签", dataIndex: "fieldName", key: "fieldName" },
  { title: "类型", dataIndex: "fieldType", key: "fieldType" },
  { title: "必填", dataIndex: "required", key: "required" },
  { title: "默认值", dataIndex: "defaultValue", key: "defaultValue" },
];

// 方法
const openModal = (record: any) => {
  // 解析数据，使用与 add-or-edit.vue 相同的逻辑
  let actualData;
  if (record.protocolData && typeof record.protocolData === 'string') {
    try {
      actualData = JSON.parse(record.protocolData);
      actualData.protocolId = record.protocolId;
      actualData.name = record.protocolName || actualData.name;

      // 处理protocolType数字转换
      let protocolType = record.protocolType || actualData.protocolType;
      if (typeof protocolType === 'number') {
        const typeMap = {
          [ProtocolTypeNumber.MERCHANT_CHANNEL_CONFIG]: ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3,
          [ProtocolTypeNumber.QR_CODE_CONFIG]: ProtocolType3.QR_CODE_CONFIG,
          [ProtocolTypeNumber.DEFAULT_PROTOCOL]: ProtocolType3.DEFAULT_PROTOCOL
        };
        protocolType = typeMap[protocolType as keyof typeof typeMap] || ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3;
      }
      actualData.protocolType = protocolType;
      actualData.channelCode = record.channelCode || actualData.channelCode;
    } catch (error) {
      console.error('解析协议数据失败:', error);
      actualData = record;
    }
  } else {
    actualData = record;
  }

  Object.assign(viewingProtocol, actualData);
  modalVisible.value = true;
};

const closeModal = () => {
  modalVisible.value = false;
};

// 辅助函数
const getProtocolTypeName = (type: string) => {
  const names = {
    MERCHANT_CHANNEL_CONFIG_V3: "商户渠道配置",
    QR_CODE_CONFIG: "二维码配置",
    DEFAULT_PROTOCOL: "默认协议",
    CHANNEL_ONBOARDING: "渠道进件协议",
  };
  return names[type as keyof typeof names] || type;
};

const getProtocolTypeColor = (type: string) => {
  const colors = {
    MERCHANT_CHANNEL_CONFIG_V3: "blue",
    QR_CODE_CONFIG: "green",
    DEFAULT_PROTOCOL: "orange",
    CHANNEL_ONBOARDING: "purple",
  };
  return colors[type as keyof typeof colors] || "default";
};

const getTotalFieldsCount = (protocol: MerchantChannelConfig3 | QRCodeConfig) => {
  return (
    protocol.configSections?.reduce(
      (total, section) => total + (section.fields?.length || 0),
      0
    ) || 0
  );
};

const getRequiredFieldsCount = (protocol: MerchantChannelConfig3 | QRCodeConfig) => {
  return (
    protocol.configSections?.reduce(
      (total, section) =>
        total + (section.fields?.filter((field) => field.required).length || 0),
      0
    ) || 0
  );
};

const getProtocolDefaultValues = (protocol: MerchantChannelConfig3 | QRCodeConfig) => {
  return ProtocolConfigUtils.getAllDefaultValues(protocol.configSections || []);
};

const formatDefaultValue = (value: any) => {
  if (value === null || value === undefined) {
    return '无';
  }
  if (typeof value === 'object') {
    return JSON.stringify(value);
  }
  if (typeof value === 'string' && value === '') {
    return '空字符串';
  }
  if (typeof value === 'boolean') {
    return value ? '是' : '否';
  }
  return String(value);
};

// 获取配置段的默认值JSON对象
const getSectionDefaultValues = (section: any) => {
  return ProtocolConfigUtils.getDefaultValues(section);
};

// 获取配置段默认值的数量
const getSectionDefaultValuesCount = (section: any) => {
  const defaultValues = getSectionDefaultValues(section);
  return Object.keys(defaultValues).length;
};

// 暴露方法给父组件调用
defineExpose({
  openModal,
  closeModal
});
</script>

<style scoped>
.protocol-view-modal {
  :deep(.ant-descriptions-item-label) {
    width: 120px;
    background-color: #fafafa;
  }
}
</style>